<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-field
        label-width="50px"
        class="username"
        v-model="username"
        name="用户名"
        placeholder="请输入手机号"
        label="用户名"
        :rules="[
          { required: true, message: '用户名不能为空' },
          { pattern: checkUserName, message: '请输入正确内容' },
        ]"
      >
      </van-field>
      <van-field
        class="psw"
        label-width="50px"
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          { pattern: checkpsw, message: '请输入正确内容' },
        ]"
      />
      <div>
        <van-button
          class="f-btn"
          round
          block
          type="info"
          native-type="submit"
          >登 录</van-button
        >
      </div>
    </van-form>
    <router-link
      class="sp"
      to="/searchpsw"
      >忘记密码</router-link
    >
  </div>
</template>
<script>
import { login } from '@/api';
import { Toast } from 'vant';
export default {
  data() {
    return {
      username: '',
      password: '',
      checkUserName: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
      checkpsw: /^\w{6,}$/,
    };
  },
  methods: {
    async onSubmit() {
      const person = {
        user_phone: this.username,
        user_pwd: this.password,
      };
      const res = await login(person);
      console.log(res);
      const {
        data: {
          code,
          msg: { results, token },
        },
      } = res;

      console.log(results);
      // const token = res.data.token;
      // localStorage.token = JSON.stringify(token || '');

      if (code == 0) {
        Toast('登录成功');
        localStorage.token = JSON.stringify(token);
        this.$store.commit('user/addUser', results[0]);
        this.$router.push('/my');
        return;
      }
      Toast('登录失败');
    },
  },
};
</script>
<style lang="scss">
.login {
  width: 84%;
  padding: 20px 8% 0 8%;
  .username {
    margin-bottom: 15px;
    border-radius: 3px;
  }
  .psw {
    margin-bottom: 15px;
    border-radius: 3px;
  }
  .f-btn {
    margin-bottom: 15px;
    font-size: 15px;
    letter-spacing: 10px;
  }
  .sp {
    display: block;
    font-size: 12px;
    color: #afafaf;
    text-align: right;
  }
}
</style>
